from rest_framework import serializers
from goods.models import SKU

class CartsSerializers(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField()
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):

        # sku_id验证, 查询商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        # 判断库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品不足')

        return attrs

class CartSerializers(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


class CartsDeleteSerializers(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):

        # sku_id验证 查询商品不存在
        try:
            sku_id = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs


class CartsSelectionSerializers(serializers.Serializer):
    selected = serializers.BooleanField(default=True)
